Skip to content

feat: support custom data dir and log directories#302

Open
JackZhao10086 wants to merge 5 commits intomainfrom
feat/linux_env_data_dir
Open

feat: support custom data dir and log directories#302
JackZhao10086 wants to merge 5 commits intomainfrom
feat/linux_env_data_dir

Conversation

@JackZhao10086
Copy link
Copy Markdown
Collaborator

@JackZhao10086 JackZhao10086 commented Apr 7, 2026

Summary

Adds environment variable overrides for keychain-related local storage paths. This lets users customize the Linux keychain data directory and the auth log directory without changing the default behavior.

Changes

  • Add LARKSUITE_CLI_DATA_DIR support in internal/keychain/keychain_other.go so Linux keychain storage can use a custom directory
  • Add LARKSUITE_CLI_LOG_DIR support in internal/keychain/auth_log.go so auth logs can be written to a custom directory

Test Plan

  • Unit tests pass
  • Manually verify relevant lark xxx commands locally

Executed:

  • go test ./internal/keychain
  • GOOS=linux GOARCH=amd64 go test -c -o /tmp/keychain_linux.test ./internal/keychain

Related Issues

Summary by CodeRabbit

  • New Features
    • Support for LARKSUITE_CLI_LOG_DIR and LARKSUITE_CLI_DATA_DIR to customize log and data locations.
  • Bug Fixes / Reliability
    • Environment-provided paths are validated and normalized; invalid or relative values are ignored and the app falls back to safe defaults.
  • Tests
    • Added unit tests covering env-based directory selection, validation, and fallback behavior.

@github-actions github-actions bot added the size/L Large or sensitive change across domains or core paths label Apr 7, 2026
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 7, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 7c97ada2-a535-4074-a41f-a98d03b56baa

📥 Commits

Reviewing files that changed from the base of the PR and between 4cb994a and d009cba.

📒 Files selected for processing (6)
  • internal/keychain/auth_log.go
  • internal/keychain/auth_log_test.go
  • internal/keychain/keychain_other.go
  • internal/keychain/keychain_other_test.go
  • internal/validate/path.go
  • internal/validate/path_test.go
✅ Files skipped from review due to trivial changes (3)
  • internal/keychain/auth_log_test.go
  • internal/validate/path_test.go
  • internal/keychain/keychain_other_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/keychain/auth_log.go
  • internal/keychain/keychain_other.go

📝 Walkthrough

Walkthrough

authLogDir() and StorageDir() now prefer env vars (LARKSUITE_CLI_LOG_DIR, LARKSUITE_CLI_DATA_DIR) and validate them via a new helper validate.SafeEnvDirPath. Added validation logic and unit tests for env-path handling, normalization, symlink resolution, and fallback behavior.

Changes

Cohort / File(s) Summary
Auth Log Directory
internal/keychain/auth_log.go
Use LARKSUITE_CLI_LOG_DIR first; validate with validate.SafeEnvDirPath; on validation failure, fall back to existing config/home-based log directory.
Storage Directory
internal/keychain/keychain_other.go
Use LARKSUITE_CLI_DATA_DIR first; validate with validate.SafeEnvDirPath; on validation failure, fall back to home-derived storage path (~/.local/share/<service>).
Path Validation Helper
internal/validate/path.go
Add SafeEnvDirPath(path, envName string) (string, error) to reject control characters, require absolute paths, clean the path, and resolve symlinks anchored at the nearest existing ancestor.
Unit Tests
internal/keychain/auth_log_test.go, internal/keychain/keychain_other_test.go, internal/validate/path_test.go
Add tests for env-var-driven paths: absolute with .. normalization and symlink resolution, relative-path rejection, and fallback-to-config/home behavior.

Sequence Diagram(s)

(omitted — changes are localized path-validation and fallback logic, not multi-component sequential flows)

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • liangshuo-1

Poem

🐰
I hopped through paths both wide and narrow,
Found env-lit trails and a safe-symlink sparrow,
I nudged the logs and stores to heed the call,
Cleaned each hop so none would trip or fall,
Happy trails where env-vars guide us all! 🥕✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat: support custom data dir and log directories' directly describes the main change—adding support for custom environment variables for data and log directories—which aligns with the core feature additions in the changeset.
Description check ✅ Passed The description covers the summary and changes sections well, and lists executed test commands; however, it is incomplete regarding manual verification and leaves the Related Issues section empty.
Docstring Coverage ✅ Passed Docstring coverage is 81.82% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/linux_env_data_dir

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@internal/keychain/auth_log.go`:
- Around line 24-26: The returned LARKSUITE_CLI_LOG_DIR value is used later by
vfs.MkdirAll and vfs.OpenFile and must be validated; update the function in
auth_log.go that reads os.Getenv("LARKSUITE_CLI_LOG_DIR") to call
validate.SafeInputPath (or the project’s equivalent) on the value and only
return it if validation succeeds, otherwise fall back to the existing default
path or an empty string and log/handle the invalid input; ensure the validation
happens before any use in vfs.MkdirAll or vfs.OpenFile so the path cannot be
used without passing validate.SafeInputPath.

In `@internal/keychain/keychain_other.go`:
- Around line 28-29: The function currently returns the raw
LARKSUITE_CLI_DATA_DIR env value (os.Getenv("LARKSUITE_CLI_DATA_DIR")) without
appending the service name, causing data/credential collisions; change the
branch in StorageDir to return filepath.Join(dir, service) instead of dir so the
environment override preserves per-service isolation (mirror the default branch
which uses filepath.Join(xdgData, service)).
- Around line 28-30: The code returns the LARKSUITE_CLI_DATA_DIR env value
directly; validate this user-controlled path with validate.SafeInputPath before
returning/using it to prevent path traversal or malformed paths. Modify the
function that reads os.Getenv("LARKSUITE_CLI_DATA_DIR") to call
validate.SafeInputPath(dir) and handle validation errors (fallback to default
dir or return an error) so all subsequent uses (the functions reading files in
this package) receive a validated path.
- Around line 28-30: The macOS StorageDir implementation (StorageDir in
keychain_darwin.go) is missing the LARKSUITE_CLI_DATA_DIR environment override
present in the other implementation (keychain_other.go); add the same env check
at the start of StorageDir in keychain_darwin.go to return that dir if set (or,
alternatively, add a comment in StorageDir documenting that the override is
intentionally Linux-only). Update the StorageDir function in keychain_darwin.go
to mirror the logic: read os.Getenv("LARKSUITE_CLI_DATA_DIR") and return it when
non-empty before falling back to the existing macOS directory resolution.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 00e3fb58-540e-40ac-8609-d64e0fdb7d01

📥 Commits

Reviewing files that changed from the base of the PR and between 6bc6bb6 and f567cc9.

📒 Files selected for processing (2)
  • internal/keychain/auth_log.go
  • internal/keychain/keychain_other.go

@github-actions
Copy link
Copy Markdown

github-actions bot commented Apr 7, 2026

🚀 PR Preview Install Guide

🧰 CLI update

npm i -g https://pkg.pr.new/larksuite/cli/@larksuite/cli@d009cba7e9ed0fae6a3831e3f9276256ee3c862a

🧩 Skill update

npx skills add larksuite/cli#feat/linux_env_data_dir -y -g

@greptile-apps
Copy link
Copy Markdown

greptile-apps bot commented Apr 7, 2026

Greptile Summary

This PR adds two environment variable overrides — LARKSUITE_CLI_DATA_DIR and LARKSUITE_CLI_LOG_DIR — allowing users to redirect Linux keychain storage and auth log directories without changing defaults. Path inputs are validated via a new SafeEnvDirPath helper that requires absolute paths, rejects control characters, and canonicalizes via resolveNearestAncestor; the previous service-scoping concern is now correctly addressed by appending the service segment after the validated base.

Confidence Score: 5/5

Safe to merge; the only finding is a P2 usability gap (missing warning on invalid env var) that does not affect correctness or data integrity.

The previous P1 concern about the service parameter being dropped is fixed. All remaining findings are P2 or lower — the silent fallback is a polish issue, not a correctness bug.

internal/keychain/auth_log.go and internal/keychain/keychain_other.go — both are missing a stderr warning when env var validation fails.

Vulnerabilities

No security concerns identified. The new SafeEnvDirPath validator correctly rejects control characters and relative paths (which could be used for path-traversal), and resolves symlinks to a canonical form before use.

Important Files Changed

Filename Overview
internal/keychain/auth_log.go Adds LARKSUITE_CLI_LOG_DIR override with path validation; silently falls back on invalid values without emitting a warning as described in the PR.
internal/keychain/keychain_other.go Adds LARKSUITE_CLI_DATA_DIR override with path validation and correct service-scoped sub-directory; same silent fallback issue as auth_log.go.
internal/validate/path.go Adds SafeEnvDirPath: requires absolute path, rejects control chars, cleans/resolves via resolveNearestAncestor — correct and well-structured.
internal/keychain/auth_log_test.go New tests cover valid env var usage and fallback on relative (invalid) paths; no build tag needed since auth_log.go is platform-agnostic.
internal/keychain/keychain_other_test.go New linux-gated tests cover valid env var with service isolation and fallback to default XDG path; correct use of build constraint.
internal/validate/path_test.go Adds tests for SafeEnvDirPath: covers relative-path rejection and canonical normalization of paths with dot-dot segments.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[authLogDir or StorageDir called] --> B{Custom env var set?}
    B -- Yes --> C[SafeEnvDirPath validate]
    C -- Valid --> D[Return custom dir plus service suffix]
    C -- Invalid --> E[Silent fallback, no warning emitted]
    B -- No --> F{LARKSUITE_CLI_CONFIG_DIR set?}
    E --> F
    F -- Yes --> G[Return CONFIG_DIR/logs]
    F -- No --> H[UserHomeDir]
    H -- ok --> I[Return default home-based path]
    H -- err --> J[Print warning to stderr and return empty-home path]
Loading

Reviews (3): Last reviewed commit: "refactor(keychain): remove warning logs ..." | Re-trigger Greptile

Add validation for environment variable directory paths to ensure they are absolute and safe. This prevents potential security issues from malformed paths. Also add corresponding tests to verify the validation behavior.
Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
internal/keychain/keychain_other_test.go (1)

10-20: Consider isolating HOME to prevent test flakiness.

Similar to the auth_log test, if LARKSUITE_CLI_DATA_DIR validation were to fail unexpectedly, this test would fall through to the HOME-based default rather than failing clearly. Isolating HOME ensures the test validates the intended code path.

🔧 Suggested improvement
 func TestStorageDir_UsesValidatedDataDirEnv(t *testing.T) {
 	base := t.TempDir()
 	base, _ = filepath.EvalSymlinks(base)
 	t.Setenv("LARKSUITE_CLI_DATA_DIR", filepath.Join(base, "data", "..", "store"))
+	t.Setenv("HOME", t.TempDir()) // Isolate from home fallback

 	got := StorageDir("svc")
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/keychain/keychain_other_test.go` around lines 10 - 20,
TestStorageDir_UsesValidatedDataDirEnv can silently pass if the
LARKSUITE_CLI_DATA_DIR validation fails because the code falls back to HOME; to
avoid flakiness, in the test (TestStorageDir_UsesValidatedDataDirEnv) explicitly
isolate HOME (e.g., set HOME to a fresh temp directory or clear it via
t.Setenv("HOME", ...) / t.Setenv("HOME", "") ) before calling StorageDir("svc")
so the test cannot accidentally succeed by using the HOME-based default,
ensuring the code path that reads and validates LARKSUITE_CLI_DATA_DIR is
exercised.
internal/keychain/auth_log_test.go (1)

8-19: Consider isolating HOME to prevent test flakiness.

The test correctly validates the LOG_DIR path, but it doesn't isolate HOME. If LARKSUITE_CLI_LOG_DIR validation were to fail unexpectedly, the test would fall through to the home-based default (${HOME}/.lark-cli/logs) rather than failing clearly.

🔧 Suggested improvement
 func TestAuthLogDir_UsesValidatedLogDirEnv(t *testing.T) {
 	base := t.TempDir()
 	base, _ = filepath.EvalSymlinks(base)
 	t.Setenv("LARKSUITE_CLI_LOG_DIR", filepath.Join(base, "logs", "..", "auth"))
 	t.Setenv("LARKSUITE_CLI_CONFIG_DIR", "")
+	t.Setenv("HOME", t.TempDir()) // Isolate from home fallback

 	got := authLogDir()
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/keychain/auth_log_test.go` around lines 8 - 19,
TestAuthLogDir_UsesValidatedLogDirEnv can fall back to the real HOME if
LARKSUITE_CLI_LOG_DIR validation fails, making the test flaky; update the test
to isolate HOME by setting a controlled value (e.g., t.Setenv("HOME",
filepath.Join(base, "nohome")) or another t.TempDir()) before calling
authLogDir(), so authLogDir() cannot accidentally read the real user home;
modify the test body around the existing env setup (LARKSUITE_CLI_LOG_DIR,
LARKSUITE_CLI_CONFIG_DIR) to also set HOME to the temporary directory to ensure
deterministic behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@internal/keychain/auth_log_test.go`:
- Around line 8-19: TestAuthLogDir_UsesValidatedLogDirEnv can fall back to the
real HOME if LARKSUITE_CLI_LOG_DIR validation fails, making the test flaky;
update the test to isolate HOME by setting a controlled value (e.g.,
t.Setenv("HOME", filepath.Join(base, "nohome")) or another t.TempDir()) before
calling authLogDir(), so authLogDir() cannot accidentally read the real user
home; modify the test body around the existing env setup (LARKSUITE_CLI_LOG_DIR,
LARKSUITE_CLI_CONFIG_DIR) to also set HOME to the temporary directory to ensure
deterministic behavior.

In `@internal/keychain/keychain_other_test.go`:
- Around line 10-20: TestStorageDir_UsesValidatedDataDirEnv can silently pass if
the LARKSUITE_CLI_DATA_DIR validation fails because the code falls back to HOME;
to avoid flakiness, in the test (TestStorageDir_UsesValidatedDataDirEnv)
explicitly isolate HOME (e.g., set HOME to a fresh temp directory or clear it
via t.Setenv("HOME", ...) / t.Setenv("HOME", "") ) before calling
StorageDir("svc") so the test cannot accidentally succeed by using the
HOME-based default, ensuring the code path that reads and validates
LARKSUITE_CLI_DATA_DIR is exercised.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: ef73e922-76e1-4c3c-94b3-9ce91e3ac652

📥 Commits

Reviewing files that changed from the base of the PR and between f567cc9 and 4cb994a.

📒 Files selected for processing (6)
  • internal/keychain/auth_log.go
  • internal/keychain/auth_log_test.go
  • internal/keychain/keychain_other.go
  • internal/keychain/keychain_other_test.go
  • internal/validate/path.go
  • internal/validate/path_test.go
✅ Files skipped from review due to trivial changes (2)
  • internal/keychain/auth_log.go
  • internal/keychain/keychain_other.go

Add missing documentation comments for SafeEnvDirPath function and related test cases to improve code clarity and maintainability
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/L Large or sensitive change across domains or core paths

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant